<?PHP
require_once("base.wpfb.php");
require_once ('src/facebook.php');

class GroupManager{

private $globalVars = null;
private $entryPageName = null;

public function __construct($pageParent) {
	$this->globalVars = new WPFB(plugin_dir_url(__FILE__));
	$this->entryPageName = $pageParent;
}

public function newGroupInsert()
{
	try{
		if( isset($_GET['save_group_id']) )
		{
			$response = $this->globalVars->fetchURL($_GET['save_group_id']);
			//echo $response;die;
			$this->globalVars->insert_CBNVRYKGSG46GHF($response,true);
			echo "<h1>Inserted information for: {$response['name']}</h1><hr/>";				
		}
		else if(isset($_GET['import_all']))
		{
			$responseData = $this->globalVars->fetchURL('me?fields=groups.fields(name,description)');
			$i = $this->globalVars->insert_ASDGKLBFUER348SL($responseData);
			echo "<h1>Inserted information for: $i groups</h1><hr/>";
		}
		$this->newGroupInsert_UI();
		$this->showGroupInformationListFromDatabase();
	}catch(Exception $e)
	{ 
		$this->globalVars->printException($e); 
		$this->newGroupInsert_UI();
	}
} // function ends here

private function newGroupInsert_UI()
{?>
	<h1>Insert group id to import group information</h1>
	<form enctype="multipart/form-data" action="<?php echo get_bloginfo('wpurl') . '/wp-admin/admin.php?page=' . $this->entryPageName ?>" method="GET">
	Group-id: <input type="text" name="save_group_id" value="00000" onfocus='this.select()' /> (must be numeric)
		<input type='hidden' name='page' value='<?PHP echo $this->entryPageName; ?>' />
		<br/><br/>
		<input type="submit" class="submit button button-primary" value="Submit"> or <a href='<?PHP bloginfo('wpurl'); echo "/wp-admin/admin.php?page={$this->entryPageName}&import_all" ?>'>Click here</a> to import all of your groups information.
	</form>
	<hr/>
<?PHP 
}

public function importPostsIntoServer()
{
	try{
		$showValueForEpocTime = 'now';
		if( isset($_GET['taskType']) && $_GET['taskType'] == 'json_to_MySqlDatabase')
		{
			$this->importJson_intoMySqlDatabase();
		}
		else if( isset($_GET['group_id']) && isset($_GET['given_epoc_hidden_value']) )
		{
			$groupID= $_GET['group_id'];
			// Stupid facebook do not mention that OAuthException happens because of passing miliseconds.
			// php cannot convert 1372674013000 to 1372674013 using intval function, so using substr
			$epoc= substr($_GET['given_epoc_hidden_value'],0,-3);
			$showValueForEpocTime = date('r', $epoc);
			
			$url = "{$groupID}/feed?fields=likes.limit(1).summary(true),comments.limit(1).summary(true),from,message,type,picture,link,id,updated_time,created_time&limit=500&until={$epoc}";
			$response = $this->globalVars->fetchURL($url);
			
			$response['group_id'] = $groupID;
			$prefix= date('d M- H_i_s', intval($epoc));
			$name= dirname(__FILE__). '\\transfer\\group_' . $prefix . '.json';
			$name = str_replace('\\', '/', $name);
			file_put_contents( $name, json_encode($response) );
			
			echo "<h1>Imported posts into: </h1>$name<hr/>";
		}
		$databaseRows = $this->globalVars->select_VMLOYTKSDVFLGDLGLD();
		if( count($databaseRows) <=0)
			throw new Exception("Please insert some group information first");
		if( isset($_GET['group_id']))
			$group_id = $_GET['group_id'];
		else
			$group_id = null;
		$this->importPostsIntoServer_UI($showValueForEpocTime, $databaseRows, $group_id);	
		$this->showGroupPostCountForEachDatabase();
	}catch(Exception $e)
	{ 
		$this->globalVars->printException($e);
		$this->importPostsIntoServer_UI('now', null, null);
	}
}
private function importPostsIntoServer_UI($showValueForEpocTime, $databaseRows, $defaultGroup)
{ ?>
	<h1>Select the group id and type the endtime of posts</h1>
	<form enctype="multipart/form-data" action="<?php echo get_bloginfo('wpurl') . '/wp-admin/admin.php?page=' . $this->entryPageName ?>" method="GET">
		Group-id: 
	<?PHP
		if( count($databaseRows) <= 0)
		{
		//<h1>Please import some value first</h1>
		?>
		
		<input type="text" name="group_id" class='big-text' value="" onfocus='this.select()' tabindex='1' /> <em>(must be numeric)</em> <br/>
		<?PHP
		}
		else
		{
			echo '<select name="group_id">';
			foreach ($databaseRows as $rows)
			{
				echo "<option value='{$rows['group_id']}'";
				if( $rows['group_id'] == $defaultGroup)
					echo 'selected="selected"';
				echo ">{$rows['name']}</option>";
			}
			echo '</select>';
		}
		
		?>
		<br/>
		Import until: <input type="text" id='given_epoc' class='big-text' size='40' value="<?PHP echo $showValueForEpocTime; ?>" tabindex='2' onfocus='this.select()' />
		
		<button id='click_me_for_date'>Convert me</button>
		<abbr title='now, yesterday, 08 May 2013 08:00:30 am, 23:59:00 etc'>Format...</abbr>
		<br/><br/>
		<div id='time_review'></div>
		
		<strong>With these options:</strong><br/>
		<input type="radio" name="taskType" value="json_to_MySqlDatabase">Json To Mysql Sever 
		<input type="radio" name="taskType" value="importPostsIntoServer" checked='checked'>Fetch posts only
		<br/>
		
		<input type='hidden' name='page' value='<?PHP echo $this->entryPageName; ?>' />
		<input type="hidden" name="given_epoc_hidden_value" id='given_epoc_hidden_value' value="00000" />
		<br/><br/>
		<input type="submit" class="submit button button-primary" value="Submit">
	</form>
	<script type='text/javascript' src='//datejs.googlecode.com/files/date.js'></script>
	<script type='text/javascript'>
	(function ($){
		$("#click_me_for_date").click(function(){
			var $inputButton= jQuery("#given_epoc");
			$inputButton.val( Date.parse($inputButton.val()));
			var epoc= new Date($inputButton.val()).getTime();
			//alert(epoc);
			$("#given_epoc_hidden_value").val(epoc);
			return false;
		});
	})(jQuery);
	</script>	
	<hr/>
<?PHP }


private function importJson_intoMySqlDatabase()
{
	try {
		$files = glob( dirname(__FILE__) . '/transfer/*.json');
		foreach($files as $file) {
			$file= str_replace('\\','/',$file);
			//do your work here
			$fetchedData= file_get_contents($file);
			$responseData= json_decode($fetchedData);
			$response= $responseData;
			$groupID = $responseData->group_id;
			
			if( count( $responseData->data) <= 0 ) continue;
			
			$i= $this->globalVars->insert_BNCVUKERJSFQWUIR($responseData, $groupID);
			unlink($file);			
			echo "<h1>Imported $i rows for $groupID</h1><hr/>";
		}			
	} catch (Exception $e) {
		$this->globalVars->printException($e);
  }
}

private function showGroupPostCountForEachDatabase()
{
	echo "<h1>Entries from database</h1>";	
	
	$databaseRows = $this->globalVars->select_BCMVBWRKDS5884XLDF();
	if( count($databaseRows) > 0)
	{
		echo '<pre><ol>';
		foreach ($databaseRows as $rows)
		{
			echo "<li>";
			print_r($rows);
			echo "</li>";
		}
		
		//print_r($databaseRows);
		echo '</ol></pre>';
		echo '<hr/>';
	}
}

private function showGroupInformationListFromDatabase()
{
	echo "<h1>Entries from database</h1>";	
	
	$databaseRows = $this->globalVars->select_VMLOYTKSDVFLGDLGLD();	
	if( count($databaseRows) > 0)
	{
		echo '<pre><ol>';
		foreach ($databaseRows as $rows)
		{
			echo "<li>{$rows['name']} => {$rows['group_id']}</li>";
		}
		
		//print_r($databaseRows);
		echo '</ol></pre>';
	}
}

} // class ends here
?>